package meta

import (
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/App/admin"
)

type Admin struct {

}

func (_ Admin) Setup() {
	Core.SetRoute("GET:/admin/setting", "[I]meta.Admin.PageAction")
	Core.SetRoute("POST:/admin/setting", "[I]meta.Admin.PostAction")
}

// setting page
func (_ Admin) PageAction(request *Core.HxRequest, response *Core.HxResponse) {
	if !admin.LoginCheck(request) {
		admin.LoginDestroy(response)
		return
	}
	data := make(map[string]interface {})
	data["Meta"] = GetAll()
	response.Body = admin.RenderAdminPage("setting.html", data, nil, "setting")
}

// update setting action
func (_ Admin) PostAction(request *Core.HxRequest, response *Core.HxResponse){
	if !admin.LoginCheck(request) {
		admin.LoginDestroy(response)
		return
	}
	data := request.Input().All()
	Update(data)
	res := map[string]interface {}{"res":true}
	response.Json(res)
}

// get all setting, return map with setting.key and setting.value
func GetAll() map[string]string {
	sql := Core.Sql("fuxiaohei_metas").Select()
	data := Core.Db.All(sql)
	res := make(map[string]string)
	for _, v := range data {
		res[v["key"]] = v["value"]
	}
	return res
}

// update setting with map by key and value
func Update(data map[string]string) {
	for k, v := range data {
		sql := Core.Sql("fuxiaohei_metas", "value").Where("key = ?").Update()
		Core.Db.Exec(sql, v, k)
	}
}

